import { useEffect, useState, useRef } from "react";
import { Modal, Spin, Button } from "antd";
import _ from "lodash";
import { CheckOutlined, RollbackOutlined } from "@ant-design/icons";
import { useScemaRender } from "../utils";
import { getPageMeta } from '@/services/request/meta';
import { IFormProps } from "@formily/core/esm/types";
import {
  formatArrayCollap,
  formatForArrayTable,
  initialSchemaNoraml,
} from "@/components/schema-form-render/utils";
import formatMsg from "@/components/schema-form-render/components/format-msg";
import { getButtons } from "@/utils/with-btns";
import ContentSlot from "@/components/schema-form-render/components/schema-form-content/content-solot";
import Draggable from 'react-draggable';
import { initForm } from "@/pages/rbrs-center/receivable/classify-rule/hooks";
import './btn.less';
interface ModalRenderFormProps {
  editData?: any;
  title: string;
  visible: boolean;
  onCancel: () => any;
  modalCode: any;
  onOk?: (values: any, cb: any) => any;
  modalMetasConfig?: any;
  metasConfig?: any;
  filedConfig?: any;
  formConfigs?: IFormProps;
  needFormat?: boolean;
  width?: number;
  needCache?: any;
  type?: any;
  eventMap?: any;
  events?:any;
  components?: any;
  remoteUrl?: any;
  remoteParams?: any;
  method?: any;
  needGroup?: boolean;
  disabled?:any;
  hooks?: any;
}
const ModalRenderForm = ({
  editData,
  title,
  visible,
  onCancel,
  metasConfig,
  modalCode,
  remoteUrl,
  remoteParams,
  method,
  filedConfig,
  formConfigs,
  needGroup = false,
  events,
  width = 900,
  type = "NORAML",
  eventMap,
  hooks,
  disabled = true,
  components,
}: ModalRenderFormProps) => {
  const [value, setValue] = useState<null | any>(null);
  const [fg, setfg] = useState<any>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const ref = useRef<any>({});
  const [isLogicLoading, setIsLogicLoading] = useState(false);
  const formRef = useRef<any>({});
  const refMap = useRef();
  const [bounds, setBounds] = useState({ left: 0, top: 0, bottom: 0, right: 0 });
  const draggleRef = useRef<HTMLDivElement>(null);

  const [remoteModalMetasConfig, setRemoteModalMetasConfig] = useState<any>({
    labelAlign: "right",
    layout: 3,
    pageDatas: [],
  });
  const { form, SchemaFormRender } = useScemaRender(
    filedConfig,
    {
      ...formConfigs,
      effects: (f: any) => {
        if (formConfigs?.effects) {
          formConfigs.effects(f);
        }
      },
    },
    '',
    true,
    [fg]
  );
  const offlineData = async () => {
    setLoading(true);
    if (metasConfig) {
      const sss: any = initialSchemaNoraml(
        _.cloneDeep(metasConfig),
        true,
        type,
        eventMap
      );
      ref.current = sss;
      if (sss && sss.result) {
        refMap.current = sss.result?.eventMap || {};
        setIsLogicLoading(true);
      }
      if (Array.isArray(sss.ArrayTableList) && sss.ArrayTableList?.length) {
        ref.current = sss;
        setRemoteModalMetasConfig(sss);
        setLoading(false);
      } else {
        ref.current = sss;
        setRemoteModalMetasConfig(sss);
        setLoading(false);
      }
    }
  };
  const getBtns = () => {
    if (ref.current?.buttons) {
      return getButtons(
        { loading, buttons: ref.current?.buttons, setLoading },
        events || eventMap, // fix: 兼容以前版本
        ""
      );
    }
    return [];
  };
  //@ts-ignore
  useEffect(async () => {
    if (modalCode) {
      try {
        const res: any = await getPageMeta(
          modalCode,
          remoteUrl,
          remoteParams,
          method
        );
        if (res.success) {
          let meta = _.cloneDeep(res.result);
          const sss: any = initialSchemaNoraml(
            meta,
            needGroup,
            type,
            eventMap
          );
          ref.current = sss;
          if (res && res.result) {
            refMap.current = res.result?.eventMap || {};
            setIsLogicLoading(true);
          }
          await formatForArrayTable(
            sss.ArrayTableList,
            sss.schema,
            type,
            eventMap
          );

          await formatArrayCollap(sss.ArrayColList, sss.schema, type, eventMap);
          setRemoteModalMetasConfig(sss);
        }
      } catch (err) {
        console.error("请求出错", err);
      }
    } else {
      if (!modalCode) return offlineData();
    }
  }, [modalCode]);
  useEffect(() => {
    if (value === null && editData && visible) {
      setValue(editData);
      console.log('editData', editData)
      form?.setValues({
        ...editData,
      });
    }
    if (!editData) {
      setValue(null);
      form?.reset();
    }
    return () => {
      setValue(null);
    };
  }, [editData, form?.id]);

  useEffect(() => {
    formRef.current = form;
  }, [form?.id]);

  const footer = () => {
    // TODO:是否需要做插入 footer 配置
    return (
      <ContentSlot
        left={
          <Button
            icon={<RollbackOutlined />}
            onClick={() => {
              setValue(null);
              form?.reset();
              onCancel();
              setfg(!fg);
            }}
          >
            {formatMsg("common.cancel")}
          </Button>
        }
        right={getBtns()}
      />
    );
  };
  const onStart = (_event: any, uiData: any) => {
    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggleRef.current?.getBoundingClientRect();
    if (!targetRect) {
      return;
    }
    setBounds({
      left: -targetRect.left + uiData.x,
      right: clientWidth - (targetRect.right - uiData.x),
      top: -targetRect.top + uiData.y,
      bottom: clientHeight - (targetRect.bottom - uiData.y),
    });
  };
  return visible ?
    <Modal
      title={title}
      visible={visible}
      width={width}
      destroyOnClose
      onCancel={() => {
        setValue(null);
        form?.reset();
        onCancel();
        setfg(!fg);
      }}
      maskClosable={false}
      confirmLoading={loading}
      footer={footer()}
      onOk={() => {
        // form.submit().then((val: any) => {
        //   const values = form.values
        //   onOk && onOk(values, () => {
        //     console.log('刷新form')
        //     setValue(null);
        //     form?.reset();
        //     //防止时间差~~
        //     setTimeout(() => {
        //       setfg(!fg);
        //     }, 250)
        //   });
        // })
      }}
      cancelButtonProps={{
        icon: <RollbackOutlined />,
      }}
      okButtonProps={{
        icon: <CheckOutlined />,
      }}
      modalRender={modal => (
        <Draggable
          disabled={disabled}
          bounds={bounds}
          onStart={(event, uiData) => onStart(event, uiData)}
        >
          <div ref={draggleRef}>{modal}</div>
        </Draggable>
      )}
    >
      <Spin spinning={loading}>
        {remoteModalMetasConfig?.schema && (
          <SchemaFormRender
            schema={remoteModalMetasConfig?.schema}
            pageConfig={remoteModalMetasConfig?.pageConfig}
          />
        )}
      </Spin>
    </Modal> : null;
};

export default ModalRenderForm;
